package com.syg.servlet03;

import com.syg.toolkit.MathKit;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 *生成图片随机验证码
 *      HttpServletResponse响应流只是将内存中产生的图片输出到了客户端
 */
@WebServlet("/verificationCode")
public class _01_VerificationCode_resp extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应头,使浏览器每隔5秒钟刷新一次
        resp.setHeader("refresh","5");
        //1.在内存中创建一张图片
        BufferedImage image = new BufferedImage(80,20, BufferedImage.TYPE_INT_RGB);
        //2.得到图片
        Graphics2D graphics2D = (Graphics2D) image.getGraphics();
        //设置图片的背景色
        graphics2D.setColor(Color.white);
        //填充背景色
        graphics2D.fillRect(0,0,80,20);
        //3.向图片上写数据
        graphics2D.setColor(Color.blue);//设置图片上字体颜色
        graphics2D.setFont(new Font(null, Font.BOLD, 20));
        graphics2D.drawString(MathKit.generateRandomNumber(), 0, 20);
        //4.设置响应头控制浏览器浏览器以图片的方式打开
        resp.setContentType("image/jpeg");//等同于resp.setHeader("Content-Type", "image/jpeg");
        //5.设置响应头控制浏览器不缓存图片数据
        resp.setDateHeader("expries", -1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");
        //6.将图片写给浏览器
        ImageIO.write(image, "jpg", resp.getOutputStream());
    }
}
